package com.mesSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mesSystem.dto.Result;
import com.mesSystem.entity.Employee;
import com.mesSystem.entity.Material;
import com.mesSystem.service.impl.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("employee")
@ResponseBody
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /**
     * 增加员工信息
     * @param employee
     * @return
     */
    @PostMapping("increase")
    public Result increase(@RequestBody Employee employee) {
        if (employee.getHireDate() == null) {
            employee.setHireDate(Date.valueOf(LocalDate.now()));
        }
        if (employee.getPassword() == null) {
            employee.setPassword("123456");
        }
        employeeService.save(employee);
        log.info("新增员工信息为：{}",employee);
        return Result.ok("保存成功～");
    }

    /**
     * 删除员工信息
     * 先查询工位-员工表，如果没有在工位-员工表中才能进行删除
     * @param employeeId
     * @return
     */
    @DeleteMapping("delete")
    public Result delete(Long employeeId) {
        return Result.ok(employeeService.removeById(employeeId));
    }

    /**
     * 查找员工信息（全部）
     * @return
     */
    @GetMapping("list")
    public Result queryEmployee() {
        List<Employee> employees = employeeService
                .query().orderByAsc("employee_id").list();
        log.info("被查询信息为：{}",employees);
        return Result.ok(employees);
    }

    /**
     * 分页查询员工信息
     */
    @GetMapping("query")
    public Result query(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "size", defaultValue = "10") Integer size) {
        // 创建分页器对象
        Page<Employee> Page = new Page<>(page, size);

        // 调用分页查询方法，将分页器传递给service
        employeeService.page(Page, new QueryWrapper<Employee>().orderByAsc("employee_id"));

        // 从分页器对象中获取分页后的数据
        List<Employee> employees = Page.getRecords();

        log.info("被查询信息为：{}", employees);

        // 返回分页结果
        return Result.ok(employees);
    }


    /**
     * 更新操作
     * @param employee
     * @return
     */
    @PostMapping("update")
    public Result update(@RequestBody Employee employee) {
        employeeService.updateById(employee);
        log.info("更新了:{}",employee);
        return Result.ok("更新成功");
    }
}
